using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System;
using System.Diagnostics;
using System.IO;

public class ExportExcelTool : AssetPostprocessor
{

    public static void OnPostprocessAllAssets(string[] importedAsset, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        var importXLSX = false;
        foreach (string str in importedAsset)
        {
            if (str.EndsWith(".xlsx"))
            {
                importXLSX = true;
            }
        }
        if (importXLSX)
        {
            UnityEngine.Debug.Log("开始转换");

            var indexPath = Path.Combine(Application.dataPath, "DataSource", "Index.xlsx");
            var package = "main";
            var csPath = Path.Combine(Application.dataPath, "Scripts", "Data", "TableData.cs");
            var binPath = Path.Combine(Application.dataPath, "Data", "tabledata.bytes");

            var process = new Process();
            process.StartInfo.FileName = Path.Combine(Application.dataPath, "Editor", "Tools", "tabtoy.exe");
            process.StartInfo.Arguments = $"-mode=v3 -index={indexPath} -package={package} -csharp_out={csPath} -binary_out={binPath}";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.WorkingDirectory = Path.Combine(Application.dataPath, "DataSource");
            process.Start();

            process.WaitForExit(1000);
            if (!process.HasExited)
            {
                process.Kill();
                UnityEngine.Debug.LogError("转换超时，强制终止");
            }
            else
            {
                UnityEngine.Debug.Log(process.StandardOutput.ReadToEnd());
                UnityEngine.Debug.Log("转换完成");
                AssetDatabase.Refresh();
            }
        }
    }
}